package com.lzp.wechat.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.lzp.wechat.common.constants.RedisConstants;
import com.lzp.wechat.common.utils.RedisCacheUtils;
import com.lzp.wechat.entity.WeiXinParameter;
import com.lzp.wechat.entity.qrCode.ActionInfo;
import com.lzp.wechat.entity.qrCode.QrCodeRequest;
import com.lzp.wechat.entity.qrCode.QrCodeResponse;
import com.lzp.wechat.entity.qrCode.Scene;
import com.lzp.wechat.service.QrCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
@Service
public class QrCodeServiceImpl implements QrCodeService {

    @Autowired
    private WeiXinParameter weiXinParameter;

    @Autowired
    private RedisCacheUtils redisCacheUtils;

    @Override
    public void createQrCode(String action_name, Integer scene_id, String scene_str, HttpServletResponse response) {
        // 1.创建二维码ticket
        String access_token = redisCacheUtils.get(RedisConstants.ACCESS_TOKEN).toString();
        String getQrCodeTicketUrl = weiXinParameter.getGetQrCodeTicketUrl();
        getQrCodeTicketUrl = getQrCodeTicketUrl.replace("TOKEN", access_token);
        Scene scene = new Scene().setScene_id(scene_id).setScene_str(scene_str);
        QrCodeRequest qrCodeRequest = new QrCodeRequest().setExpire_seconds(604800).setAction_name(action_name).setAction_info(new ActionInfo(scene));
        String result = HttpUtil.post(getQrCodeTicketUrl, JSON.toJSONString(qrCodeRequest));
        log.info("调用腾讯创建二维码ticket响应：{}", result);
        QrCodeResponse qrCodeResponse = JSON.parseObject(result, QrCodeResponse.class);
        // 2.通过ticket换取二维码
        String showQrCodeUrl = weiXinParameter.getShowQrCodeUrl();
        showQrCodeUrl = showQrCodeUrl.replace("TICKET", qrCodeResponse.getTicket());
        byte[] bytes = HttpUtil.downloadBytes(showQrCodeUrl);
        try {
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
